//
//  YUHomeViewController.swift
//  tuniu
//
//  Created by 于世民 on 2019/8/8.
//  Copyright © 2019 于世民. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import RxDataSources
import ReusableKit
import MJRefresh

class YUHomeViewController: YUBaseViewController, YURefreshable {
    
    var refreshHeader: MJRefreshHeader!
    
    private var collectionView: UICollectionView!
    
    let disposeBag = DisposeBag()
    
    private var viewModel = YUHomeViewModel()
    
    private var vmOutput: YUHomeViewModel.YUHomeOutput?
    
    var dataSoure: RxCollectionViewSectionedReloadDataSource<YUHomeSection>!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        zy_barAlpha = 0
        
        title = ""
        
        initUI()
        
        bindUI()
    }
    
}

extension YUHomeViewController {
    
    private func initUI() {
        let layout = YUHomeFlowLayout()
        collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: kScreenH - kNavibarH - 20), collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.white
        collectionView.showsVerticalScrollIndicator = false
        view.addSubview(collectionView)
        
        if #available(iOS 11.0, *) {
            collectionView.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
            automaticallyAdjustsScrollViewInsets = false
        }
        
        collectionView.rx.setDelegate(self).disposed(by: rx.disposeBag)
        
        collectionView.register(Reusable.recommendCell)
        collectionView.register(YUHomeTopReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "YUHomeTopReusableView")
    }
    
    private func bindUI() {
        
        dataSoure = RxCollectionViewSectionedReloadDataSource<YUHomeSection>(configureCell: { (ds, cv, indexPath, item) -> UICollectionViewCell in
            
            let cell = cv.dequeue(Reusable.recommendCell, for: indexPath)
            cell.item = item.advertises?[indexPath.item]
            return cell
            
        }, configureSupplementaryView: { (ds, cv, kind, indexPath) in
            let top = ds[indexPath.section].items
            
            if kind == UICollectionView.elementKindSectionHeader {
                
                let topView = cv.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "YUHomeTopReusableView", for: indexPath) as! YUHomeTopReusableView
                
                let pic = top[0].advertises?.map({ (model) -> String in
                    return model.image
                })
                
                topView.picArr.value = pic ?? []
                
                return topView
            }
            
            return UICollectionReusableView()
        })
        
        vmOutput = viewModel.transform(input: YUHomeViewModel.YUHomeInput())
        
        //输出绑定
        vmOutput?.sections.asDriver().drive(collectionView.rx.items(dataSource: dataSoure)).disposed(by: rx.disposeBag)
    
        refreshHeader = initRefreshGifHeader(collectionView) { [weak self] in
            self?.vmOutput?.requestCommand.onNext(true)
        }
        
        vmOutput?.autoSetRefreshHeaderStatus(header: refreshHeader, footer: nil).disposed(by: disposeBag)
        
        refreshHeader.beginRefreshing()

    }
    
}

extension YUHomeViewController: UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        return YUHomeCollectionViewCell.itemSize()
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
        return YUHomeCollectionViewCell.itemSize()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

        return UIEdgeInsets.zero
    }
}

private enum Reusable {
    
    static let recommendCell = ReusableCell<YUHomeCollectionViewCell>(nibName: "YUHomeCollectionViewCell")
  
}
